package applet;

import java.applet.Applet;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.util.ArrayList;

import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

/**
 * Enables user to fetch (or subscribe?) to display messages posted to the
 * system and exchanged among chat peers
 * 
 * @author Chris (claimed >= Rev26)
 */
public class MessageBoard extends Applet {
	
	private static final long serialVersionUID = -9139034459056627015L;
	// class variables
	JScrollPane scrollablePane;
	TextArea bulletinBoard;
	ArrayList<ChatMessage> messages = new ArrayList<ChatMessage>();
	String boardMessages;

	/** applet lifecycle is started by init()**/
	public void init() {
		bulletinBoard = new TextArea();
		scrollablePane = new JScrollPane(bulletinBoard);
		scrollablePane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		JScrollBar vScrollBar = new JScrollBar();
		vScrollBar.setToolTipText("hi");
		vScrollBar.setEnabled(true);
		scrollablePane.setVerticalScrollBar(vScrollBar);
		scrollablePane.setWheelScrollingEnabled(true);
		this.add(scrollablePane);
		this.setLayout(new GridLayout());
	}

	/**adds a message to this Client's board ie: for later display**/
	public void addMessage(String user, String message) {
		ChatMessage chatMessage = new ChatMessage(user, message);
		messages.add(chatMessage);
		displayMessages();
	}

	/**retrieve all messages added in externally-usable format**/
	public String getAllMessages() {
		return boardMessages;
	}

	// call from .html/.js
	/** output all this clients' messages for display by the browser */
	public void displayMessages() {

		boardMessages = "";
		for (ChatMessage msg : messages) {
			boardMessages += msg.getMessage() + "\n";
		}
		bulletinBoard.setText(boardMessages);
		this.repaint();
	}// end method

	/**
	 *************************************************************
	 ********THE METHODS BEYOND HERE ARE FOR TESTING**************
	 *************************************************************
	**/
	// a no-arg addMessage() method (added,FOR TESTING ONLY!)
	public void addMessage() {
		removeTopMessage();
		addMessage("System", "no arg test message method");
	}

	// method for testing ONLY!
	public void removeTopMessage() {
		messages.remove(0);
	}
	
	/**
	 ****************************************
	 *****END TEST-METHODS-ONLY SECTION******
	 ****************************************
	/**
	 * inner class
	 **/
	private class ChatMessage {
		// variables
		String u;
		String mesg;

		// inner-class constructor
		ChatMessage(String user, String message) {
			this.u = user;
			this.mesg = message;
		}

		String getMessage() {
			return u + ": " + mesg + "\n";
		}
	}
}
